<?php
session_start();
require_once '../config/database.php';

if (!is_admin()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

$search = $_GET['search'] ?? '';

if ($search) {
    // Query for existing car titles in our database
    $query = "SELECT DISTINCT c.title, b.id as brand_id, b.name as brand_name, m.id as model_id, m.name as model_name 
              FROM cars c 
              LEFT JOIN brands b ON c.brand_id = b.id 
              LEFT JOIN models m ON c.model_id = m.id 
              WHERE c.title LIKE ?";
    
    $stmt = $db->prepare($query);
    $stmt->execute(['%' . $search . '%']);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Query external car database API for suggestions
    $apiUrl = "https://car-data.p.rapidapi.com/cars?limit=10&page=0&year=2020&make=" . urlencode($search);
    $apiResults = [];
    
    try {
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-RapidAPI-Host: car-data.p.rapidapi.com',
            'X-RapidAPI-Key: YOUR_API_KEY_HERE'  // Replace with your RapidAPI key
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        
        if ($response) {
            $apiData = json_decode($response, true);
            foreach ($apiData ?? [] as $car) {
                if (stripos($car['name'], $search) !== false) {
                    $apiResults[] = [
                        'title' => $car['make'] . ' ' . $car['model'] . ' ' . $car['year'],
                        'brand_id' => null,
                        'brand_name' => $car['make'],
                        'model_id' => null,
                        'model_name' => $car['model']
                    ];
                }
            }
        }
    } catch (Exception $e) {
        error_log('Car API Error: ' . $e->getMessage());
    }

    // Merge and deduplicate results
    $allResults = array_merge($results, $apiResults);
    $uniqueResults = array_unique($allResults, SORT_REGULAR);

    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'results' => array_values($uniqueResults)]);
} 